<div class="layuimini-container layuimini-page-anim">
    <div class="layuimini-main">

        <blockquote class="layui-elem-quote layui-text">
            辅导员上传集体档案照片，注意集体档案照片题名：“河南大学**学院**届（**）级**系**专业**班毕业合影”
        </blockquote>
        <form class="layui-form" action="">
            <script type="text/javascript">
                function getFileUrl(sourceId) {
                    var url;
                    if (navigator.userAgent.indexOf("MSIE") >= 1) { // IE
                        url = document.getElementById(sourceId).value;
                    } else if (navigator.userAgent.indexOf("Firefox") > 0) { // Firefox
                        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
                    } else if (navigator.userAgent.indexOf("Chrome") > 0) { // Chrome
                        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
                    }
                    return url;
                }

                function preImg(sourceId, targetId) {
                    var url = getFileUrl(sourceId);
                    var imgPre = document.getElementById(targetId);
                    imgPre.src = url;
                }
            </script>
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
                <legend>照片上传</legend>
            </fieldset>

            <div class="layui-inline">
                <label class="layui-form-label">选择要上传的集体照</label>
                <div class="layui-input-inline">
                    <input type="file" name="imgOne" id="imgOne" onchange="preImg(this.id,'photo');"/>
                </div>
            </div>
            <br>
            <img src="images/test.png" id="photo">

            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
                <legend>相册信息</legend>
            </fieldset>
            <div class="layui-form-item">
                <label class="layui-form-label">相册标题</label>
                <div class="layui-input-inline">
                    <textarea name="title" autocomplete="off" placeholder="河南大学**学院**届（**）级**系**专业**班毕业合影"
                              class="layui-input"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">拍摄日期</label>
                <div class="layui-input-inline">
                    <input type="text" name="date" id="date" lay-verify="date" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">拍摄地点</label>
                <div class="layui-input-inline">
                    <input type="text" name="title" lay-verify="title" autocomplete="off" placeholder="请输入拍摄地点"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">班级人数</label>
                <div class="layui-input-inline">
                    <input type="number" name="title" lay-verify="title" autocomplete="off" placeholder="请输入班级人数"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">参与人数</label>
                <div class="layui-input-inline">
                    <input type="number" name="title" lay-verify="title" autocomplete="off" placeholder="请输入参与拍摄人数"
                           class="layui-input">
                </div>
            </div>
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
                <legend>人员详细信息</legend>
            </fieldset>
            <div class="layui-form-item number-of-people-body">
                <label class="layui-form-label">第1排：</label>
                <div class="layui-input-inline" style="width: 4rem">
                    <input type="number" lay-verify="number-of-people" autocomplete="off" placeholder="人数"
                           class="layui-input number-of-people">
                </div>
                <button class="layui-btn number-of-people-btn" type="button">生成姓名格</button>
            </div>

            <button class="layui-btn number-of-people-btn2" type="button" id="new-row-btn">添加一排</button>
        </form>
        <center>
            <button class="layui-btn number-of-people-btn2" type="button" id="save-btn" lay-submit lay-filter="saveBtn">
                保存
            </button>
        </center>

    </div>
</div>
<style>
</style>
<script>
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate;

        /**
         * 初始化表单，要加上，不然刷新部分组件可能会不加载
         */
        form.render();

        //日期
        laydate.render({
            elem: '#date'
        });
        laydate.render({
            elem: '#date1'
        });

        //创建一个编辑器
        var editIndex = layedit.build('LAY_demo_editor');

        //自定义验证规则
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            }
            , pass: [
                /^[\S]{6,12}$/
                , '密码必须6到12位，且不能出现空格'
            ]
            , content: function (value) {
                layedit.sync(editIndex);
            }
        });

        //监听指定开关
        form.on('switch(switchTest)', function (data) {
            layer.msg('开关checked：' + (this.checked ? 'true' : 'false'), {
                offset: '6px'
            });
            layer.tips('温馨提示：请注意开关状态的文字可以随意定义，而不仅仅是ON|OFF', data.othis)
        });

        //监听提交
        form.on('submit(saveBtn)', function (data) {
            var albumId = localStorage.getItem("selectedAlbumId");
            var isPub = true;
            if (data.field.isPublic === 'off') {
                isPub = false;
            }
            var peopleRow = [];
            var people = [];

            //获取每行人员信息
            var peopleBody = jq1111('.number-of-people-body');
            for (i = 0; i < peopleBody.length; i++) {
                var rowNames = peopleBody.eq(i).children();
                for (j = 3; j < rowNames.length; j++) {
                    var SB = {
                        "name": rowNames.eq(j).children().val(),
                        "row": i,
                        "col": j - 3,
                    };
                    console.log(SB)
                    people.push(SB);
                }
                people.push(peopleRow);
                peopleRow = [];
            }

            console.log('people', people)

            var formData = new FormData();
            formData.append('isPublic', isPub)
            formData.append('title', data.field.title);
            formData.append('description', data.field.describe);
            formData.append('shootingDate', data.field.date);
            formData.append('location', data.field.location);
            formData.append("file", jq1111("#imgOne")[0].files[0]);
            formData.append('people', JSON.stringify(people));
            console.log(jq1111("#upload-file"))
            jq1111.ajax({
                type: "POST",
                crossDomain: true,
                url: BasePath + "api/resource/upload",
                processData: false,
                contentType: false,
                dataType: "json",
                xhrFields: {
                    withCredentials: true
                },
                data: formData,
                success: function (message) {
                    console.log(message);
                    layer.alert(message.msg, {
                        title: '操作结果'
                    })
                },
                error: function (message) {
                    console.log(message.responseJSON);
                    layer.alert(message.responseJSON.msg, {
                        title: '操作结果'
                    })
                },
            });

            return false;
        });
    });

    layui.use(['jquery'], function () {
        //生成姓名格
        var numberBtn = jq1111(".number-of-people-btn");
        for (i = 0; i < numberBtn.length; i++) {
            jq1111(numberBtn[i]).bind("click", {index: i}, clickHandler)
        }

        function clickHandler(event) {
            var i = event.data.index;
            var input = jq1111(numberBtn[i]).prev().children();
            var numberOfNameInput = jq1111(numberBtn[i]).parent().children().length;
            var inputNumber = parseInt(input.val())
            if (numberOfNameInput > inputNumber + 3) {
                for (t = 0; t < numberOfNameInput - inputNumber - 3; t++) {
                    var itemBodyEq = jq1111(numberBtn[i]).parent()
                    jq1111(itemBodyEq.children()[4]).remove();
                }
                numberOfNameInput = jq1111(numberBtn[i]).parent().children().length;
            } else {
                for (j = 0; j < (inputNumber + 3 - numberOfNameInput); j++) {
                    var itemBodyEq = jq1111(numberBtn[i]).parent()
                    itemBodyEq.eq(0).append('<div class="layui-input-inline" style="width: 5rem"><input  name="number-of-people-1" placeholder="姓名" class="layui-input number-of-people-name"></div>')
                }
                numberOfNameInput = jq1111(numberBtn[i]).parent().children().length
            }
        }

        // 生成行

        var counnum = 2;
        jq1111("#new-row-btn").click(function () {
            jq1111(".number-of-people-body").last().after('<div class="layui-form-item number-of-people-body"><label class="layui-form-label">第' + counnum + '排：</label><div class="layui-input-inline" style="width: 4rem"><input  type="number" lay-verify="number-of-people" autocomplete="off" placeholder="人数" class="layui-input number-of-people"></div><button id="' + counnum + '" class="layui-btn number-of-people-btn" type="button">生成姓名格</button></div>')
            jq1111(".number-of-people-body").on("click", '#' + counnum, addBtnHander);
            counnum++;
            form.render();
        })
        // jq1111(".number-of-people-body").on("click",'#1',addBtnHander)
        // jq1111(".number-of-people-body").on("click",'#1',clickHandler)
        function addBtnHander() {
            var peopleBody = jq1111('.number-of-people-body');
            var rowNames = peopleBody.eq(counnum - 2).children();
            console.log(counnum,rowNames)
            for (j = 3; j < rowNames.length; j++) {
                rowNames.eq(j).remove();
            }
            var num = parseInt(jq1111(this).prevAll().eq(0).children().val());
            if (num < 0 | NaN) return
            for (var i = 0; i < num; i++) {
                jq1111(this).prev().parent().append('<div class="layui-input-inline" style="width: 5rem"><input  name="number-of-people-1" placeholder="姓名" class="layui-input number-of-people-name"></div>');
            }
        }

    });

</script>

